package com.yuwei.module_sign.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import com.yuwei.module_sign.R

class CircleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = DEFAULT_STROKE_WIDTH
        strokeCap = Paint.Cap.ROUND
        color = DEFAULT_COLOR
    }

    private val rectF = RectF()
    private var currentAngle = 0f
    private lateinit var animator: ValueAnimator

    // 默认值
    companion object {
        private const val DEFAULT_STROKE_WIDTH = 20f
        private val DEFAULT_COLOR = Color.BLUE
        private const val DEFAULT_ANIMATION_DURATION = 1000L // 1秒
    }

    init {
        setupAttributes(attrs)
        setupAnimator()
    }

    private fun setupAttributes(attrs: AttributeSet?) {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.CircleView)
            paint.color = typedArray.getColor(R.styleable.CircleView_circle_color, DEFAULT_COLOR)
            paint.strokeWidth = typedArray.getDimension(
                R.styleable.CircleView_stroke_width,
                DEFAULT_STROKE_WIDTH
            )
            typedArray.recycle()
        }
    }

    private fun setupAnimator() {
        animator = ValueAnimator.ofFloat(0f, 360f).apply {
            duration = DEFAULT_ANIMATION_DURATION
            interpolator = AccelerateDecelerateInterpolator()
            addUpdateListener { animation ->
                currentAngle = animation.animatedValue as Float
                invalidate()
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val padding = paint.strokeWidth / 2
        rectF.set(
            padding,
            padding,
            width - padding,
            height - padding
        )

        canvas.drawArc(rectF, -90f, currentAngle, false, paint)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startAnimation()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAnimation()
    }

    fun startAnimation() {
        if (!animator.isRunning) {
            animator.start()
        }
    }

    fun stopAnimation() {
        if (animator.isRunning) {
            animator.cancel()
        }
    }

    fun setCircleColor(color: Int) {
        paint.color = color
        invalidate()
    }

    fun setStrokeWidth(width: Float) {
        paint.strokeWidth = width
        invalidate()
    }
}